package org.shj.spark.core;

import java.util.List;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.PairFunction;

import scala.Tuple2;

public class TopN {

	public static void main(String[] args) {
		SparkConf conf = new SparkConf().setMaster("local").setAppName("TopN");
		JavaSparkContext sc = new JavaSparkContext(conf);
		
		JavaRDD<String> lines = sc.textFile("topN.txt", 2);
		JavaPairRDD<Integer, Integer> numberRDD = lines.mapToPair(new PairFunction<String, Integer, Integer>(){
			private static final long serialVersionUID = -2171725714887060169L;

			@Override
			public Tuple2<Integer, Integer> call(String line) throws Exception {
				return new Tuple2<Integer, Integer>(Integer.parseInt(line), 1);
			}
		});
		
		List<Tuple2<Integer, Integer>> take = numberRDD.sortByKey(false).take(3);
		for(Tuple2<Integer, Integer> top : take){
			System.out.println(top._1);
		}
		
		sc.close();

	}

}
